package icu.sehnen.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import icu.sehnen.user.entity.Permission;
import icu.sehnen.user.mapper.PermissionMapper;
import icu.sehnen.user.service.IPermissionService;
import icu.sehnen.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService {
    @Autowired
    PermissionMapper permissionMapper;
    @Autowired

    IUserService userService;

    @Override
    public List<Permission> getMenusById(Long id) {

        return  getMenusByUserId(id);
    }

    @Override
    public List<Permission> getPermission() {
        QueryWrapper<Permission> queryWrapper=new QueryWrapper();
        queryWrapper.eq(false,"id",0);
        List<Permission> permissionList = permissionMapper.selectList(queryWrapper);
        return  buildMenuTree(permissionList,0l);

    }


    public List<Permission> getPermissionsByUserId(Long id) {
        List<Permission> permissionList=permissionMapper.getPermissionByUserId(id) ;
        return permissionList;

    }


    public List<Permission> getMenusByUserId(Long id) {
        List<Permission> rootMenu = getPermissionsByUserId(id);
        return buildMenuTree(rootMenu,0L);
    }

    private List<Permission> buildMenuTree(List<Permission> menuList, Long pid) {
        List<Permission> treeList = new ArrayList<>();
        menuList.forEach(menu -> {
            if (pid.equals(menu.getPid())) {
                menu.setChildren(buildMenuTree(menuList, menu.getId()));
                treeList.add(menu);
            }
        });
        return treeList;
    }
}